import React, { useReducer, useEffect } from "react";

const defaultState = {
  count: 5,
};

const reducer = (state, action) => {
  switch (action.type) {
    case "add":
      return {
        ...state,
        count: state.count + 1,
      };
    case "minus":
      return {
        ...state,
        count: state.count - 1,
      };
    default:
      return state;
  }
};

const App = () => {
  // useReducer函数可以接收两个参数，第一个是reducer函数，第二个是defaultState
  // 执行会返回一个数组，state和dispatch
  // 并且直接有响应式
  const [state, dispatch] = useReducer(reducer, defaultState);

  useEffect(() => {
    // 请求数据，去执行dispatch
  }, []);

  return (
    <>
      <h3>useReducer</h3>
      <button onClick={() => dispatch({ type: "minus" })}>-</button>
      <span>{state.count}</span>
      <button onClick={() => dispatch({ type: "add" })}>+</button>
    </>
  );
};

export default App;
